//
//  TJHomeController.m
//  CrossBorderPayment
//
//  Created by hc-101 on 2020/6/9.
//  Copyright © 2020 xtjun. All rights reserved.
//





#import "TJHomeController.h"
#import "TJHomeHeaderView.h"
#import "TJHomeCell.h"
#import "TJScanController.h"
#import <AVFoundation/AVCaptureDevice.h>
#import "TJHomeDetailController.h"
#import "TJSettingMoneyPasswordController.h"

@interface TJHomeController ()

@property (strong, nonatomic) NSArray <TJHomeModel *>*datas;

@property (weak, nonatomic) TJHomeHeaderView *headerView;
@property (nonatomic, weak) NSTimer *timer;

@end

static NSString * const homeCell = @"homeCell";


@implementation TJHomeController

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.timer setFireDate:[NSDate distantFuture]];
    
}
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.timer setFireDate:[NSDate distantPast]];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //隐藏导航栏
    self.navigationBar.hidden = YES;
    
    [self setUpUI];
    
    [self updateVersion];
    

    
    NSTimer *timer =  [NSTimer timerWithTimeInterval:5.0 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    self.timer = timer;
    
    
}
- (void)timerRun {
    [self loadData];
}
- (void)setUpUI {
    
    UIImageView *topView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 118 + StatusBarHeight - 20)];
    [self.view addSubview:topView];
    topView.userInteractionEnabled = YES;
    topView.image = [UIImage imageNamed:@"homeBg_icon"];
    topView.contentMode = UIViewContentModeScaleAspectFill;
    
    UIButton *collectionButton = [UIButton buttonWithSuperView:topView font:UIFont_Px(14) color:UIColor.whiteColor title:@"收款".localizedString];
    [collectionButton setImage:[UIImage imageNamed:@"collectMoney"] forState:UIControlStateNormal];
    [collectionButton setImage:[UIImage imageNamed:@"collectMoney"] forState:UIControlStateHighlighted];
    collectionButton.tag = 1002;
    [collectionButton addTarget:self action:@selector(didClickCollectionButton) forControlEvents:UIControlEventTouchUpInside];
    [collectionButton setImagePosition:LXMImagePositionTop spacing:6];
    [collectionButton setContentHorizontalAlignment:(UIControlContentHorizontalAlignmentCenter)];
    [collectionButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.offset(60);
        make.centerX.mas_offset(0);
        make.centerY.mas_offset((StatusBarHeight - 20) * 0.5 + 10);
        
        make.height.offset(80);
    }];
    
    UIButton *scanButton = [UIButton buttonWithSuperView:topView font:UIFont_Px(14) color:UIColor.whiteColor title:@"扫一扫".localizedString];
    scanButton.tag = 1001;
    [scanButton setImage:[UIImage imageNamed:@"scanIcon"] forState:UIControlStateNormal];
    [scanButton setImage:[UIImage imageNamed:@"scanIcon"] forState:UIControlStateHighlighted];
    [scanButton addTarget:self action:@selector(didClickScanButton) forControlEvents:UIControlEventTouchUpInside];
    [scanButton setContentHorizontalAlignment:(UIControlContentHorizontalAlignmentCenter)];
    [scanButton setImagePosition:LXMImagePositionTop spacing:6];
    [scanButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.offset(60);
        make.left.offset(44);
        make.centerY.equalTo(collectionButton);
        make.height.offset(80);
    }];
    
    
    UIButton *transferButton = [UIButton buttonWithSuperView:topView font:UIFont_Px(14) color:UIColor.whiteColor title:@"转账".localizedString];
    transferButton.tag = 1003;
    [transferButton setImage:[UIImage imageNamed:@"transferIcon"] forState:UIControlStateNormal];
    [transferButton setImage:[UIImage imageNamed:@"transferIcon"] forState:UIControlStateHighlighted];
    [transferButton addTarget:self action:@selector(didClickTransferButton) forControlEvents:UIControlEventTouchUpInside];
    [transferButton setImagePosition:LXMImagePositionTop spacing:6];
    [transferButton setContentHorizontalAlignment:(UIControlContentHorizontalAlignmentCenter)];
    [transferButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.offset(60);
        make.centerY.equalTo(collectionButton);
        make.right.offset(-44);
        make.height.offset(80);
    }];
    
    UIButton *buyButton = [UIButton buttonWithSuperView:self.view font:UIFont_Px(18) color:UIColor.whiteColor title:@"法币交易".localizedString];
    buyButton.backgroundColor = UIColor.tj_mainColor;
    [buyButton shearRoundedCornersWithRadiu:3];
    [buyButton addTarget:self action:@selector(didClickBuyButton) forControlEvents:UIControlEventTouchUpInside];
    [buyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-34);
        make.left.offset(34);
        make.height.offset(44);
        make.centerX.offset(0);
        make.top.equalTo(topView.mas_bottom).offset(25);
    }];
    
    
    TJHomeHeaderView *headerView = [[TJHomeHeaderView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 220)];
    
    
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.rowHeight = 98;
    self.tableView.backgroundColor = UIColor.whiteColor;
    self.tableView.tableHeaderView = headerView;
    
    [self.tableView registerClass:TJHomeCell.self forCellReuseIdentifier:homeCell];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(buyButton.mas_bottom).offset(25);
        make.left.offset(10);
        make.right.offset(-10);
        make.bottom.offset(0);
    }];
    
    _headerView = headerView;
}
#pragma mark ---------------按钮点击------------------
/**转账按钮点击 **/
- (void)didClickTransferButton {
    [self.navigationController pushViewControllerWithName:@"TJTransferController" title:nil animated:YES];
}
/**收款按钮点击 **/
- (void)didClickCollectionButton {
    if (!TJUserInfo.readInfo.payPassword.replacingEmptyString.length) {
        
        [self alertWithTitle:nil message:@"请先设置资金密码".localizedString leftButtonName:@"取消".localizedString rightButtonName:@"前往设置".localizedString leftButtonBlock:nil rightButtonBlock:^{
            //0，未绑定,1已绑定
            TJSettingMoneyPasswordController *settingMoneyPasswordController = [[TJSettingMoneyPasswordController alloc] init];
            [settingMoneyPasswordController setComplete:^{
                [TJNetworking.shareNetworking updateUserInfoAndLoading:NO success:^(TJUserInfo * _Nonnull userInfo) {
                    
                }];
            }];
            [self.navigationController pushViewController:settingMoneyPasswordController animated:YES];
        }];
        
        
        return;
    }
    [self.navigationController pushViewControllerWithName:@"TJCollectMoneyController" title:nil animated:YES];
}
/**首页扫一扫按钮点击 **/
- (void)didClickScanButton {
    
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (granted) {
                TJScanController *scanController = [[TJScanController alloc] init];
                [scanController setScanComplete:^(NSString * _Nonnull result) {
                    
                    [TJQrcodeResultHandler QrCodeResultHandlerWithController:self result:result];
                }];
                [self presentViewController:scanController animated:YES completion:nil];
            }
        });
    }];
    
    AVAuthorizationStatus authStatus =  [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied) {
        [self alertWithTitle:nil message:@"不能使用相机,前往开启？".localizedString leftButtonName:@"取消".localizedString rightButtonName:@"前往开启".localizedString leftButtonBlock:nil rightButtonBlock:^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
        }];
        return;
    }
}
/**法币交易点击 **/
- (void)didClickBuyButton {
    [self.navigationController pushViewControllerWithName:@"TJBuySellControntroller" title:nil animated:YES];
}

#pragma mark ---------------数据请求------------------
- (void)loadData {
    [TJNetworking.shareNetworking GET:@"member/balance/getBalanceList" parameters:@{@"userId": TJUserInfo.readInfo.userId} success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        
        if (![data isKindOfClass:NSDictionary.class]) return;
        self.headerView.dict = data;
        self.datas = [TJHomeModel mj_objectArrayWithKeyValuesArray:data[@"balances"]];
        
        [self.tableView reloadData];
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
    
}
#pragma mark ---------------UITableViewDataSource, UITableViewDelegate------------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TJHomeCell *cell = [tableView dequeueReusableCellWithIdentifier:homeCell forIndexPath:indexPath];
    cell.backgroundColor = UIColor.whiteColor;
    cell.model = self.datas[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    
    TJHomeDetailController *homeDetailController = [[TJHomeDetailController alloc] init];
    //    homeDetailController.model = self.datas[indexPath.row];
    [self.navigationController pushViewController:homeDetailController animated:YES];
    
    
}
#pragma mark ---------------updateVersion------------------
- (void)updateVersion {
    
    [TJNetworking.shareNetworking GET:@"member/member/appVersion" parameters:@{@"id": @"1"} success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        
        NSString *serviceVersion = data[@"version"];
        serviceVersion = [serviceVersion stringByReplacingOccurrencesOfString:@"." withString:@""];
        serviceVersion = [serviceVersion stringByReplacingOccurrencesOfString:@"," withString:@""];
        
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *currentlyVersions = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        currentlyVersions = [currentlyVersions stringByReplacingOccurrencesOfString:@"." withString:@""];
        currentlyVersions = [currentlyVersions stringByReplacingOccurrencesOfString:@"," withString:@""];
        
        NSString *content = data[@"content"];
        content = [content stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];
        
        if (serviceVersion.intValue > currentlyVersions.intValue) {
            BOOL isForced = [data[@"updateFlag"] intValue];//updateFlag 0不强制更新 1强制更新
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"发现新版本".localizedString message:content preferredStyle:UIAlertControllerStyleAlert];
            if (!isForced) [alert addAction:[UIAlertAction actionWithTitle:@"取消".localizedString style:UIAlertActionStyleDefault handler:nil]];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定".localizedString style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:data[@"versionUrl"]] options:@{} completionHandler:nil];
                [self presentViewController:alert animated:YES completion:nil];
            }]];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
        
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
    
}
- (void)dealloc {
    
    [self.timer invalidate];
    self.timer = nil;
    NSLog(@"%s", __func__);
}
#pragma mark ---------------状态栏颜色------------------
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

@end
